<?php
class LetterIn extends AppModel {
    var $validate = array(
        'letter_from' => array(
            'required' => true,
            'allowEmpty' => false,
            'rule' => '/\w+[\w\s]/',
            'message' => 'Field ini tidak boleh kosong'
        ),
        'letter_no' => array(
            'required' => true,
            'allowEmpty' => false,
            'rule' => '/\w+/',
            'message' => 'Field ini tidak boleh kosong'
        ),
        'letter_date' => array(
            'required' => true,
            'allowEmpty' => false,
            'rule' => 'date',
            'message' => 'Isi tanggal surat'
        ),
        'disposition_date' => array(
            'required' => true,
            'allowEmpty' => false,
            'rule' => 'date',
            'message' => 'Isi tanggal disposisi'
        ),
        'unit_code_id' => array(
            'rule' => array('vUnit'),
            'message' => 'Pilih unit kerja pemroses'
        ),
        'term_code_id' => array(
            'required' => true,
            'allowEmpty' => false,
            'rule' => array('vTerm'),
            'message' => 'Choose based on available options'
        )
    );

    var $belongsTo = array(
        'UnitCode', 'TermCode',
        'User' => array(
            'className' => 'User',
            'foreignKey' => 'created_by',
            'fields' => array('id', 'name')
        )
    );
    
    var $hasMany = array(
        'LetterInImage' => array(
            'dependent' => true
        )
    );

    var $cacheQueries = true;
    
    function vUnit($field) {
        $exist = $this->UnitCode->find('count', array(
            'conditions' => array(
                'UnitCode.id' => $field["unit_code_id"]
            ),
            'recursive' => -1)
        );
        return $exist > 0;
    }
    
    function vTerm($field) {
        $exist = $this->TermCode->find('count', array(
            'conditions' => array(
                'TermCode.id' => $field["term_code_id"]
            ),
            'recursive' => -1)
        );
        return $exist > 0;
    }
    
/**
 * Qty per month based on year and whom create that (user or unit)
 * used by ReportsController::grafik
 * $per null means all unit codes
 */
    function getQtyPerMonth($year, $by, $per = null) {
        $WHERE = ' WHERE ';
        if ( $by == 'u' ) {
            if ( $per ) {
                $WHERE .=  "unit_code_id = $per ";
            } else {
                $WHERE .= "1=1 ";
            }
        } else {
            if ( $per ) {
                $WHERE .=  "created_by = $per ";
            } else {
                $WHERE .= "1=1 ";
            }
        }
        
        $WHERE .= "AND created >= '$year-01-01 00:00:00' AND created <= '$year-12-31 23:59:59'";
        
        return $this->query("SELECT COUNT(id) as qty, DATE_FORMAT(created, '%m') as m FROM `letter_ins` $WHERE  GROUP BY m");
    }
}
?>
